import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Code, Copy, Trash2, CheckCircle, AlertCircle } from 'lucide-react';

/**
 * JSON 格式化工具
 * 支持格式化、验证和美化 JSON
 */
export default function JsonFormatter() {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState(false);

  // 格式化 JSON
  const formatJson = () => {
    try {
      setError(null);
      setSuccess(false);

      if (input.trim() === '') {
        setError('请输入 JSON 内容');
        return;
      }

      const parsed = JSON.parse(input);
      const formatted = JSON.stringify(parsed, null, 2);
      setOutput(formatted);
      setSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : '无效的 JSON 格式');
      setOutput('');
    }
  };

  // 压缩 JSON
  const minifyJson = () => {
    try {
      setError(null);
      setSuccess(false);

      if (input.trim() === '') {
        setError('请输入 JSON 内容');
        return;
      }

      const parsed = JSON.parse(input);
      const minified = JSON.stringify(parsed);
      setOutput(minified);
      setSuccess(true);
    } catch (err) {
      setError(err instanceof Error ? err.message : '无效的 JSON 格式');
      setOutput('');
    }
  };

  // 复制结果
  const copyOutput = () => {
    if (output) {
      navigator.clipboard.writeText(output);
      alert('已复制到剪贴板！');
    }
  };

  // 清空所有
  const clearAll = () => {
    setInput('');
    setOutput('');
    setError(null);
    setSuccess(false);
  };

  // 示例 JSON
  const loadExample = () => {
    const example = {
      name: 'Feng Admin',
      version: '2.0',
      features: ['动态路由', '微应用', 'JSON格式化'],
      config: {
        theme: 'dark',
        language: 'zh-CN',
      },
      active: true,
    };
    setInput(JSON.stringify(example));
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">JSON 格式化工具</h1>
          <p className="text-muted-foreground">验证、格式化和美化 JSON 数据</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={loadExample}>
            加载示例
          </Button>
          <Button variant="outline" onClick={clearAll}>
            <Trash2 className="mr-2 h-4 w-4" />
            清空
          </Button>
        </div>
      </div>

      {/* 操作按钮 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex flex-wrap gap-3">
            <Button onClick={formatJson}>
              <Code className="mr-2 h-4 w-4" />
              格式化
            </Button>
            <Button variant="secondary" onClick={minifyJson}>
              压缩
            </Button>
            <Button variant="outline" onClick={copyOutput} disabled={!output}>
              <Copy className="mr-2 h-4 w-4" />
              复制结果
            </Button>
            {success && (
              <Badge className="ml-auto flex items-center gap-1 bg-green-600">
                <CheckCircle className="h-3 w-3" />
                处理成功
              </Badge>
            )}
            {error && (
              <Badge
                variant="destructive"
                className="ml-auto flex items-center gap-1"
              >
                <AlertCircle className="h-3 w-3" />
                {error}
              </Badge>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 输入和输出 */}
      <div className="grid gap-4 lg:grid-cols-2">
        {/* 输入 */}
        <Card className="h-[calc(100vh-20rem)]">
          <CardHeader>
            <CardTitle>输入 JSON</CardTitle>
          </CardHeader>
          <CardContent className="h-[calc(100%-5rem)]">
            <textarea
              value={input}
              onChange={(e) => setInput(e.target.value)}
              className="h-full w-full resize-none rounded-md border bg-background p-4 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring"
              placeholder='粘贴或输入 JSON，例如：{"name": "value"}'
            />
          </CardContent>
        </Card>

        {/* 输出 */}
        <Card className="h-[calc(100vh-20rem)]">
          <CardHeader>
            <CardTitle>格式化结果</CardTitle>
          </CardHeader>
          <CardContent className="h-[calc(100%-5rem)]">
            <textarea
              value={output}
              readOnly
              className="h-full w-full resize-none rounded-md border bg-muted p-4 font-mono text-sm focus:outline-none"
              placeholder="格式化后的 JSON 将显示在这里..."
            />
          </CardContent>
        </Card>
      </div>
    </div>
  );
}

